class Solution:
    def maxScore(self, cardPoints: list, k: int) -> int:
        memo = {}

        def func(points, i, j, k):
            if k == 0:
                return 0
            if (i, j) in memo:
                return memo[(i, j)]
            score = max(points[i] + func(points, i + 1, j, k - 1),
                        points[j] + func(points, i, j - 1, k - 1))

            memo[(i, j)] = score
            return score

        return func(cardPoints, 0, len(cardPoints) - 1, k)
